#!/bin/bash

# Curl Converter Docker 构建和部署脚本

set -e

# 配置变量
IMAGE_NAME="curlconverter-webui"
TAG="${1:-latest}"
CONTAINER_NAME="curlconverter-webui"
PORT="${2:-3000}"

echo "🚀 开始构建 Curl Converter Docker 镜像..."

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "❌ Docker 未安装，请先安装 Docker"
    exit 1
fi

# 停止并删除现有容器（如果存在）
if [ "$(docker ps -aq -f name=$CONTAINER_NAME)" ]; then
    echo "🛑 停止现有容器..."
    docker stop $CONTAINER_NAME || true
    docker rm $CONTAINER_NAME || true
fi

# 构建镜像
echo "📦 构建 Docker 镜像..."
docker build -t $IMAGE_NAME:$TAG .

# 运行容器
echo "🌟 启动容器..."
docker run -d \
    --name $CONTAINER_NAME \
    -p $PORT:80 \
    --restart unless-stopped \
    $IMAGE_NAME:$TAG

# 等待容器启动
echo "⏳ 等待容器启动..."
sleep 5

# 检查容器状态
if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
    echo "✅ 容器启动成功！"
    echo "🌐 访问地址: http://localhost:$PORT"
    echo "📊 容器状态: $(docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' -f name=$CONTAINER_NAME)"
else
    echo "❌ 容器启动失败"
    echo "查看日志: docker logs $CONTAINER_NAME"
    exit 1
fi

echo ""
echo "📋 有用的命令:"
echo "  查看日志: docker logs $CONTAINER_NAME"
echo "  停止容器: docker stop $CONTAINER_NAME"
echo "  重启容器: docker restart $CONTAINER_NAME"
echo "  删除容器: docker rm -f $CONTAINER_NAME"
echo "  删除镜像: docker rmi $IMAGE_NAME:$TAG"